﻿using System;
using System.Collections.Generic;

namespace Fadd
{
    /// <summary>
    /// Pool of items
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Pool<T>
    {
        private readonly Func<T> _factoryMethod;
        private readonly Queue<T> _items = new Queue<T>();

        /// <summary>
        /// Initializes a new instance of the <see cref="Pool&lt;T&gt;"/> class.
        /// </summary>
        /// <param name="factoryMethod">The factory method.</param>
        /// <remarks>
        /// The factory method is invoked when the pool is empty and a new
        /// item is needed.
        /// </remarks>
        public Pool(Func<T> factoryMethod)
        {
            _factoryMethod = factoryMethod;
        }

        /// <summary>
        /// Dequeue item (or create a new one if pool is empty)
        /// </summary>
        /// <returns></returns>
        public T Dequeue()
        {
            lock (_items)
            {
                if (_items.Count > 0)
                    return _items.Dequeue();
            }

            return _factoryMethod();
        }

        public void Enqueue(T item)
        {
            lock (_items)
                _items.Enqueue(item);
        }
    }
}